#include "../../head/utils/MutiSignalDecode.h"
#include "../../head/utils/SendSerialUtil.h"
#include "../../head/mainwindow.h"
#include <QDateTime>
#include <QMessageBox>
#include <QTextStream>
#include <QtDebug>
#include <QTextCodec>
#include "../../head/utils/MutiConfFile.h"
#include "../../head/utils/tcpclient.h"
#include "../../head/dbpsk/DownlinkDemodulator.h"
#include "../../head/dbpsk/DownlinkDeframing.h"
#include "../../head/dbpsk/DBPSK_Demodulator.h"
#include "../../head/dbpsk/OFDM_Frame.h"
extern TcpClient client_;

MutiSignalDecode::MutiSignalDecode(QObject *parent):QObject(parent)
{
    //MutiConfFile *mcf_low = new MutiConfFile();

    //mcf_low->createFile();
    //return;
     //mcf_low->readFile(this->baseUrl+"conf_low.ini",this->baseUrl+"InitParam_low.ini");
    //return ;
    init_Param(LOW);
    //init_Param(HIGH);
    // mcf_low->deleteFile(this->baseUrl+"InitParam_low.ini");
   // init_Param(HIGH);

     if(DemodParam[0]->Demodule_Mode == 153){ //0x99 psk_psk
        //MutiConfFile *mcf_high = new MutiConfFile();
       // mcf_high->readFile(this->baseUrl+"conf_high.ini",this->baseUrl+"InitParam_high.ini");
        init_Param(HIGH);

        //mcf_high->deleteFile(this->baseUrl+"InitParam_high.ini");

        for (int i = 0; i < DemodParam[0]->PreSignal_Len; i++) {
            this->MudSigStand[LOW]->Pri[i] = 0;
            this->MudSigStand[HIGH]->Pri[i] = 0;
        }
        this->demodule(HIGH);
        this->demodule(LOW);
     }else if(DemodParam[0]->Demodule_Mode == 152){ //0x98 dbpsk
         DownlinkDemodulatorInit();
     }
}

/**
*  \brief  多路串口解调，初始化解调参数.
*
*
**/
void MutiSignalDecode::init_Param(int hzType)
{
    int j=0,i=hzType;

    record_log("function initParam() InitParam_"+iniPortType[i]+".ini START");
    QTextCodec *code = QTextCodec::codecForName("gb2312");    //打开系统配置文件
    QString str_conf_url = baseUrl+"InitParam_"+iniPortType[i]+".ini";
    std::string stdConfStr = code->fromUnicode(str_conf_url).toStdString();
    char const* confFilePath = stdConfStr.c_str();
    INIFileStream[i] = OpenINIFile(confFilePath);

    if (INIFileStream[i] == NULL){
        printf("OPEN FAILED!!1");
        record_log("OPEN FAILED!!1");
        //ERROR(INIFileStream);
    }

    DemodParam[i] = (PtrDemodParam)malloc(sizeof(VarDemodParam));
    DemodulatorParamSet(INIFileStream[i], C_DATA_FRAME_LEN_BIT, PressureSensorNum, &Fc_Hz_read[i], &Rb_bps_read[i], &ModuleEnableStatus[i], DemodParam[i]);


    Fc_Hz[i] =32000000/(128*4 * CountN[(int)Fc_Hz_read[i]-1]) * Rb_bps_read[i]; //3125,1953,1250,977; %  载波频率/最后一个数表示采用子信道号
    Rb_bps[i] =32000000/(128*4* CountN[(int)Fc_Hz_read[i]-1]);  //3125,1953,1250,977; %  符号率

    Actual_Len[i] = Rb_bps[i] * SAMPNUM_PERSYMBOL;

    qDebug()<<"Fc_Hz=="<<Fc_Hz[i]<<";;;;Rb_bps==="<<Rb_bps[i]<<";;;;Actual_Len==="<<Actual_Len[i]<<endl;
    record_log("Fc_Hz=="+QString::number(Fc_Hz[i], 'f', 2)+",;;;;Rb_bps==="+QString::number(Rb_bps[i], 'f', 2)+",;;;;Actual_Len==="+QString::number(Actual_Len[i], 'f', 2));


    //为结构体指针分配内存
    DemodulatorS_PriCh[i] = (PtrDemodulatorStruct)malloc(sizeof(VarDemodulatorStruct));
    DemodulatorS_PriCh[i]->PreFilterStructRef = NULL;//单通道 此部分结构体指针为空指针  双通道此部分结构体指针分配内存
    DemodulatorS_PriCh[i]->DecimatorStructRef = NULL;
    DemodulatorS_PriCh[i]->DSNC_Struct = NULL;
    DemodulatorS_PriCh[i]->PreFilterStruct = (PtrPreFilterStruct)malloc(sizeof(VarPreFilterStruct));
    DemodulatorS_PriCh[i]->PreFilterStruct1 = (PtrPreFilterStruct)malloc(sizeof(VarPreFilterStruct));
    DemodulatorS_PriCh[i]->FpumpMeasureStruct = (PoPumpStruct)malloc(sizeof(VarPumpStruct));
    DemodulatorS_PriCh[i]->DecimatorStruct = (PtrDecimator)malloc(sizeof(VarDecimator));
    DemodulatorS_PriCh[i]->DecimatorStruct1 = (PtrDecimator)malloc(sizeof(VarDecimator));
    DemodulatorS_PriCh[i]->BPSK_DemodStruct = (PtrBPSKDemodStruct)malloc(sizeof(VarBPSKDemodStruct));
    DemodulatorS_PriCh[i]->ModuleStructFSRC = (PtrFarrowStruct)malloc(sizeof(VarFarrowStruct));
    DemodulatorS_PriCh[i]->CarrierDPLLStruct = (PtrCarrierDPLLStruct)malloc(sizeof(VarCarrierDPLLStruct));
    DemodulatorS_PriCh[i]->ModuleStructFrameSync = (PtrFrameSyncStruct)malloc(sizeof(VarFrameSyncStruct));
    DemodulatorS_PriCh[i]->ModuleStructFrameSyncBuf = (PtrBufStruct)malloc(sizeof(VarBufStruct));
    DemodulatorS_PriCh[i]->ModuleStructEq = (PrtEqualizerDFEStruct)malloc(sizeof(VarEqualizerDFEStruct));
    DemodulatorS_PriCh[i]->ChirpDetectionStruct = (PtrChirpDetectionStruct)malloc(sizeof(VarChirpDetectionStruct));//ADD chirp检测
    DemodulatorS_PriCh[i]->MedFilterStruct = (PtrMedFilterStruct)malloc(sizeof(VarMedFilterStruct));//ADD MedFilter

    //2022.12.01
    Probe[i] = (PtrProbe)malloc(sizeof(VarProbe));
    memset(Probe[i], 0, sizeof(VarProbe));

    MudSigStand[i] = (PtrMudSig)malloc(sizeof(VarMudSig));
    memset(MudSigStand[i], 0, sizeof(VarMudSig));

    //为泥浆脉冲信号分配内存
    MudSigStand[i]->Pri = NEW(DemodParam[i]->PreSignal_Len, double);
    MudSigStand[i]->Ref = NEW(DemodParam[i]->PreSignal_Len, double);

    //模块初始化
    DemodulatorInit(INIFileStream[i],Fc_Hz_read[i], Fc_Hz[i], Rb_bps[i], DemodulatorS_PriCh[i], DemodParam[i], ModuleEnableStatus[i],i);

    //2023-02-03 add
    save_source_data[i] = DemodulatorParamSetByName(INIFileStream[i],"SYSTEM_SETTING","SOURCE_DATA");
    ZoomIn[i] =  DemodulatorParamSetByName(INIFileStream[i],"BaseParameter","ZoomIn");
    sys_zgcd[i] = DemodulatorParamSetByName(INIFileStream[i],"SYSTEM_SETTING","ZGCD");

    if (!CloseINIFile(INIFileStream[i]))//文件使用完毕，
    {
        printf("\nclose file faild!\n");
    }

    //为Probe里的指针动态分配内存
    Probe[i]->SigBB = NEW(2 * DemodParam[i]->PreSignal_Len, double);//经过初始化后为Farrow_SigLen赋值z

    Probe[i]->SigBB_Frw = NEW(2 * (DemodulatorS_PriCh[i]->ModuleStructFSRC->Farrow_SigLen), double);//经过初始化后为Farrow_SigLen赋值z
    Probe[i]->SyncedSigOut = NEW(2 * (DemodulatorS_PriCh[i]->ModuleStructFSRC->Farrow_SigLen), double);
    Probe[i]->MseqCorrOut = NEW(DemodulatorS_PriCh[i]->ModuleStructFSRC->Farrow_SigLen, double);
    Probe[i]->FrameSyncSig = NEW(DemodulatorS_PriCh[i]->ModuleStructFSRC->Farrow_SigLen, int);
    Probe[i]->CarrierLocI = NEW(DemodulatorS_PriCh[i]->ModuleStructFSRC->Farrow_SigLen, double);
    Probe[i]->CarrierLocQ = NEW(DemodulatorS_PriCh[i]->ModuleStructFSRC->Farrow_SigLen, double);
    Probe[i]->SigBB_AFC = NEW(2 * (DemodulatorS_PriCh[i]->ModuleStructFSRC->Farrow_SigLen), double);
    Probe[i]->EqSig = NEW(2 * ((DemodParam[i]->TRAINING_SEQ_LEN) + MAX_RBPS), double);
    Probe[i]->DecData = NEW(2 * ((DemodParam[i]->TRAINING_SEQ_LEN) + MAX_RBPS), double);
    Probe[i]->EqErr = NEW(2 * ((DemodParam[i]->TRAINING_SEQ_LEN) + MAX_RBPS), double);
    Probe[i]->SigPreFilt = NEW(DemodParam[i]->PreSignal_Len, double);
    Probe[i]->SigMedFilt = NEW(DemodParam[i]->PreSignal_Len, double);
    Probe[i]->SignalDenoise = NEW(DemodParam[i]->PreSignal_Len, double);

    fft_in[i] = (double *)fftw_malloc(sizeof( double) * DataPrimary_BUF_SIZE);
    fft_out[i] = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * DataPrimary_BUF_SIZE);

    fifoDecByte[i].Buf = (double*)malloc(DEC_FIFOBYTESize * sizeof(double));
    fifoDec[i].Buf = (double*)malloc(DEC_FIFOSize * sizeof(double));

    memset(fifoDecByte[i].Buf,0,DEC_FIFOBYTESize* sizeof(double));
    fifoDecByte[i].nWp=0;
    fifoDecByte[i].nRp=0;
    fifoDecByte[i].nUsedCnt=0;
    fifoDecByte[i].deep=DEC_FIFOBYTESize;

    countDec[i].CoutByte = 0;
    countDec[i].nCoutBitCnt_ModByte = 0;
    countDec[i].nCoutBitCnt_ModFrame = 0;

    memset(fifoDec[i].Buf,0,DEC_FIFOSize* sizeof(double));
    fifoDec[i].nWp=0;
    fifoDec[i].nRp=0;
    fifoDec[i].nUsedCnt=0;
    fifoDec[i].deep=DEC_FIFOSize;

    for(j = 0; j < DataPrimary_BUF_SIZE; j++){
        DataPrimary_Temp[i][j]=0;
        Data_SignalDenoise[i][j]=0;
    }

    for(j = 0; j < DataPrimary_BUF_SIZE/2; j++){
        DataPrimary_Fre_Temp[i][j]=0;
    }

    for(j = 0; j < MseqCorrOut_PriCh_TempSize; j++){
        MseqCorrOut_PriCh_Temp[i][j]=0;
    }

    for(j = 0; j < EQ_ALL_ERR_LEN; j++){
        EqSig_PriCh_Temp_I[i][j]=0;
        EqSig_PriCh_Temp_Q[i][j]=0;
        EqErr_PriCh_Temp[i][j]=0;
    }

    record_log("function initParam() InitParam_"+iniPortType[i]+".ini  FINISHED!!!");


}



//记录错误日志
void MutiSignalDecode::record_log(QString message){
//     qDebug()<<"message="<<message<<endl;
//     if(message.size() > 1){
//        //打开写日志文件

//        QTextCodec *code = QTextCodec::codecForName("gb2312");
//        std::string stdlogFilePath = code->fromUnicode(str_log_url).data();
//        char const* logFilePath = stdlogFilePath.c_str();
//        FOPEN(logfile, logFilePath, "a+");	//保存 log信息，在程序结束时closefile


//        QByteArray qaLogTime = logTime.toLatin1();
//        const char *cLogTime = qaLogTime.data();
//        QByteArray qaMessage = message.toLatin1();
//        const char *qMessage = qaMessage.data();
//        fprintf(logfile,"%s %s\n",cLogTime,qMessage);
//        fclose(logfile);
//     }

    QDateTime curDateTime = QDateTime::currentDateTime();
    QString str_log_url = baseUrl+"logs/"+curDateTime.toString("yyyy-MM-dd")+".txt";
    QTextCodec *code = QTextCodec::codecForName("gb2312");
    //另存为
    QFile fileWrite(QString::fromLocal8Bit(code->fromUnicode(str_log_url)));
    if(fileWrite.open(QIODevice::WriteOnly|QIODevice::Text|QIODevice::Append)){        //文件流写文件
        QTextStream streamWrite(&fileWrite);      //通过文本流控制文件写操作
        QString logTime = curDateTime.toString("yyyy-MM-dd hh:mm:ss");
        streamWrite<<logTime<<":"<<message<<endl;;
    }
    fileWrite.close();


}


/**
*  \brief  处理解调后的数据.
*  \param [in] hzType  高频低频区分
*
*
**/
void MutiSignalDecode::demodule_DecData(int hzType){
    int mSeqLen = DemodParam[hzType]->TRAINING_SEQ_LEN;
    double xzb = 0;

    FILE *fid;
    QDateTime curDateTime = QDateTime::currentDateTime();
    QString save_url = baseUrl+"source/"+curDateTime.toString("yyyy-MM-dd hh")+"_decdata.txt";
    QTextCodec *code = QTextCodec::codecForName("gb2312");
    std::string stdStr = code->fromUnicode(save_url).data();
    char const* save_url_ = stdStr.c_str();
    fid = fopen(save_url_, "a+");

    for(int i = 0 ;i < Probe[hzType]->DecData_Len ; i++ ){
        fifoDec[hzType].Buf[fifoDec[hzType].nWp] = Probe[hzType]->DecData[i];

        fifoDec[hzType].nWp = fifoDec[hzType].nWp+1;
        if(fifoDec[hzType].nWp > fifoDec[hzType].deep - 1){
            fifoDec[hzType].nWp=0;
        }
        fifoDec[hzType].nUsedCnt = fifoDec[hzType].nUsedCnt+1;
    }

    if(fifoDec[hzType].nUsedCnt>=2){
        for(int i = 0 ; i < EQ_ALL_ERR_LEN/2;i++){
            xzb =  xzb + pow(sqrt(pow(EqErr_PriCh_Temp[hzType][2*i],2)+pow(EqErr_PriCh_Temp[hzType][2*i+1],2)),2);
        }

        double singnalEfficiency = (double)1.0/(xzb/EQ_ALL_ERR_LEN)/1.5;
        df->showSignalInfo(singnalEfficiency,hzType); //显示信噪比
        hf->showSignalInfo(singnalEfficiency,hzType);
    }

    while( fifoDec[hzType].nUsedCnt > 0 ) {
        if (countDec[hzType].nCoutBitCnt_ModFrame < mSeqLen) { //输出M序列

            if (countDec[hzType].nCoutBitCnt_ModFrame == mSeqLen-1 ) {//M序列最后一位换行
                emit sendDeCodeData("DATA",hzType);
                fprintf(fid,"DATA \n");

            }
            fifoDec[hzType].nRp = fifoDec[hzType].nRp + 1;
            if (fifoDec[hzType].nRp > fifoDec[hzType].deep - 1) {
                fifoDec[hzType].nRp = 0;
            }
            fifoDec[hzType].nUsedCnt = fifoDec[hzType].nUsedCnt - 1;
            countDec[hzType].nCoutBitCnt_ModFrame = MOD(countDec[hzType].nCoutBitCnt_ModFrame + 1, DemodParam[hzType]->DATA_FRAME_LEN_BIT);
        } else {//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%输出解调数据
            countDec[hzType].CoutByte = countDec[hzType].CoutByte + fifoDec[hzType].Buf[fifoDec[hzType].nRp] * pow(2,(countDec[hzType].nCoutBitCnt_ModByte));
            fifoDec[hzType].nRp = fifoDec[hzType].nRp + 1;
            if (fifoDec[hzType].nRp > fifoDec[hzType].deep - 1) {
                fifoDec[hzType].nRp = 0;
            }
            fifoDec[hzType].nUsedCnt = fifoDec[hzType].nUsedCnt - 1;
            if (countDec[hzType].nCoutBitCnt_ModByte == 7) { //够一个字节时输出并保存到字节FIFO_DEC_Byte内
                fifoDecByte[hzType].Buf[fifoDecByte[hzType].nWp] = countDec[hzType].CoutByte;
                fifoDecByte[hzType].nWp = MOD(++fifoDecByte[hzType].nWp,fifoDecByte[hzType].deep - 1);
                fifoDecByte[hzType].nUsedCnt = fifoDecByte[hzType].nUsedCnt + 1;

                //在console显示解调完的数据
                QString qs00 = QString("%1").arg(countDec[hzType].CoutByte,2,16,QLatin1Char('0')).toUpper();
               //qDebug()<<"data == ::" <<qs00<<endl;
                std::string stdqs00 = qs00.toStdString();
                char const* saveqs00_ = stdqs00.c_str();
                fprintf(fid,"%s \t",saveqs00_);                                 
               emit sendDeCodeData(qs00,hzType);
                if(mutiSerialControl->sendDecDataPort->isOpen()){
                    QByteArray tempDecData1;
                    tempDecData1.append(countDec[hzType].CoutByte);
                    mutiSerialControl->sendDecDataPort->write(tempDecData1);                    
                }else{
                    this->record_log("QIODevice::write (QSerialPort): device not open....");
                }

                if(QAbstractSocket::ConnectedState ==client_.state()){
                    QByteArray tempDecData1;
                    tempDecData1.append(countDec[hzType].CoutByte);

                    client_.write(tempDecData1);
                    client_.waitForBytesWritten(100);

                }else{
                     this->record_log("TcpSockect: TcpSockect is unConnectedState....");
                }

                countDec[hzType].CoutByte = 0;
            }
            if (countDec[hzType].nCoutBitCnt_ModFrame == DemodParam[hzType]->DATA_FRAME_LEN_BIT - 1) {
                fprintf(fid,"\n");

            }
            countDec[hzType].nCoutBitCnt_ModByte = MOD(++countDec[hzType].nCoutBitCnt_ModByte,8);
            countDec[hzType].nCoutBitCnt_ModFrame = MOD(++countDec[hzType].nCoutBitCnt_ModFrame, DemodParam[hzType]->DATA_FRAME_LEN_BIT);
        }

    }
    fclose(fid);


//    while(fifoDecByte[hzType].nUsedCnt >= 1){
//        tempRead2[hzType] = fifoDecByte[hzType].Buf[fifoDecByte[hzType].nRp];
//        fifoDecByte[hzType].nRp = MOD(++fifoDecByte[hzType].nRp,fifoDecByte[hzType].deep - 1);
//        fifoDecByte[hzType].nUsedCnt = fifoDecByte[hzType].nUsedCnt - 1;


//        if(tempRead1[hzType] == 170 && tempRead2[hzType] == 170){ //  十六进制AA AA;
//            // qDebug()<<"AAAA OK..."<<endl;
//            this->record_log("AAAA OK...");
//            sendDecData[hzType].clear();
//            sendDecData[hzType].append(tempRead1[hzType]);
//            StateN[hzType] = 1;
//        }

//        if(StateN[hzType] == 1){
//            sendDecData[hzType].append(tempRead2[hzType]);
//        }

//        tempRead1[hzType] = tempRead2[hzType];

//        if(hzType == LOW){

//            for(int i = 0; i < SEND_PARAMS_SIZE ; i++){
//                if(sendDecData[LOW].size() == sendParams[i][1]
//                        &&sendDecData[LOW][2] == sendParams[i][0]){
//                    tempListData[hzType].clear();
//                    tempListData[hzType].append(sendDecData[LOW]);
//                }

//            }


//            for(int i = 0; i < SEND_PARAMS_SIZE ; i++){
//                if(sendDecData[HIGH].size() == sendParams[i][1]
//                        &&sendDecData[HIGH][2] == sendParams[i][0]){

//                        for(int j = 0; j < SEND_PARAMS_SIZE ; j++){
//                             if(tempListData[LOW].size() == sendParams[j][1]
//                                     &&tempListData[LOW][2] == sendParams[j][0]){
//                                QByteArray tempDecData;
//                                QString tempStr;

//                                for(int dec = 0;dec < tempListData[hzType].size();dec ++){
//                                    tempDecData.append(tempListData[hzType][dec]);
//                                    int ll = tempListData[hzType][dec];
//                                    tempStr += QString("%1").arg(ll,2,16,QLatin1Char('0')).toUpper() + " ";
//                                }
//                                this->record_log(tempStr);
//                                if(mutiSerialControl->sendDecDataPort != NULL){
//                                    if(mutiSerialControl->sendDecDataPort->isOpen()){
//                                        mutiSerialControl->sendDecDataPort->write(tempDecData);
//                                    }else{
//                                        this->record_log("QIODevice::write (QSerialPort): device not open....");
//                                    }
//                                }

//                                if(QAbstractSocket::ConnectedState ==client_.state()){
//                                    client_.write(tempDecData);
//                                    client_.waitForBytesWritten(100);

//                                }else{
//                                     this->record_log("TcpSockect: TcpSockect is unConnectedState....");
//                                }

//                                StateN[LOW] = 0;
//                                sendDecData[LOW].clear();
//                                StateN[HIGH] = 0;
//                                sendDecData[HIGH].clear();
//                                tempListData[LOW].clear();
//                                tempListData[HIGH].clear();

//                            }
//                        }

//                    }

//                }

//        }



//        if(hzType == LOW){
//            if((sendDecData[LOW].size() == DEC_FIVE_LENGTH &&sendDecData[LOW][2] != 1)
//                    ||  (sendDecData[LOW].size() == DEC_LONG_LENGTH &&sendDecData[LOW][2] == 1)){
//                tempListData[hzType].clear();
//                tempListData[hzType].append(sendDecData[LOW]);
//            }

//            if((sendDecData[HIGH].size() == DEC_FIVE_LENGTH &&sendDecData[HIGH][2] != 1)
//                            ||  (sendDecData[HIGH].size() == DEC_LONG_LENGTH &&sendDecData[HIGH][2] == 1)){


//                 if((tempListData[LOW].size() == DEC_FIVE_LENGTH &&tempListData[LOW][2] != 1)
//                          ||  (tempListData[LOW].size() == DEC_LONG_LENGTH &&tempListData[LOW][2] == 1)){

//                    QByteArray tempDecData;
//                    QString tempStr;

//                    for(int dec = 0;dec < tempListData[hzType].size();dec ++){
//                        tempDecData.append(tempListData[hzType][dec]);
//                        int ll = tempListData[hzType][dec];
//                        tempStr += QString("%1").arg(ll,2,16,QLatin1Char('0')).toUpper() + " ";
//                    }
//                    this->record_log(tempStr);
//                    if(mutiSerialControl->sendDecDataPort != NULL){
//                        if(mutiSerialControl->sendDecDataPort->isOpen()){
//                            mutiSerialControl->sendDecDataPort->write(tempDecData);
//                        }else{
//                            this->record_log("QIODevice::write (QSerialPort): device not open....");
//                        }
//                    }

//                    if(QAbstractSocket::ConnectedState ==client_.state()){
//                        client_.write(tempDecData);
//                        client_.waitForBytesWritten(100);

//                    }else{
//                         this->record_log("TcpSockect: TcpSockect is unConnectedState....");
//                    }

//                    StateN[LOW] = 0;
//                    sendDecData[LOW].clear();
//                    StateN[HIGH] = 0;
//                    sendDecData[HIGH].clear();

//                }

//            }
//        }

  //  }
}



/**
*  \brief  串口收数后调用解调主程序.
*  \param [in] hzType  高频低频区分
*
*
**/
void MutiSignalDecode::demodule(int hzType){
    QT_TRY{
        int i = 0,len = 0,start = 0;

        //解调地面数据

        Demodulator(MudSigStand[hzType],DemodulatorS_PriCh[hzType],ModuleEnableStatus[hzType],Probe[hzType],DemodParam[hzType],frame_counter);

        len = Actual_Len[hzType] / 2;
        start = MseqCorrOut_PriCh_TempSize - len;

        for(i = 0 ; i < start;i++){
            MseqCorrOut_PriCh_Temp[hzType][i] = MseqCorrOut_PriCh_Temp[hzType][i+len];
        }

        for(i = 0 ; i < len ;i++){
            MseqCorrOut_PriCh_Temp[hzType][start+i] = Probe[hzType]->MseqCorrOut[i];
        }


        len = Probe[hzType]->EqSigCnt / 2;
        start = EQ_ALL_ERR_LEN - len;
        for(i = 0 ; i < start;i++){
            EqErr_PriCh_Temp[hzType][i] = EqErr_PriCh_Temp[hzType][i+len];
            EqSig_PriCh_Temp_I[hzType][i] = EqSig_PriCh_Temp_I[hzType][i+len];
            EqSig_PriCh_Temp_Q[hzType][i] = EqSig_PriCh_Temp_Q[hzType][i+len];
        }

        for(i = 0 ; i < len ;i++){
            EqErr_PriCh_Temp[hzType][start+i] = sqrt(pow(Probe[hzType]->EqErr[i * 2], 2) + pow(Probe[0]->EqErr[i * 2 + 1], 2));
            EqSig_PriCh_Temp_I[hzType][start+i] = Probe[hzType]->EqSig[i * 2];
            EqSig_PriCh_Temp_Q[hzType][start+i] = Probe[hzType]->EqSig[i * 2 + 1];
        }


        len = DemodParam[hzType]->PreSignal_Len;
        start = DataPrimary_BUF_SIZE - len;
        for(i = 0 ; i < start;i++){
            DataPrimary_Temp[hzType][i] = DataPrimary_Temp[hzType][i+len];
            Data_SignalDenoise[hzType][i] = Data_SignalDenoise[hzType][i+len];
        }

        for(i = 0 ; i < len ;i++){
            DataPrimary_Temp[hzType][start+i] = MudSigStand[hzType]->Pri[i];
            Data_SignalDenoise[hzType][start+i] = Probe[hzType]->SignalDenoise[i];
        }
        //fft 采样数据解调开始
        for (i = 0; i <DemodParam[0]->ADC_Fs_Hz*2; i++){
            fft_in[hzType][i] = DataPrimary_Temp[hzType][i];
        }

        my_plan[hzType] = FFTW3_H::fftw_plan_dft_r2c_1d(DemodParam[0]->ADC_Fs_Hz*2, fft_in[hzType], fft_out[hzType], FFTW_ESTIMATE);
        fftw_execute(my_plan[hzType]);
        len = DataPrimary_BUF_SIZE/2;
        for(i = 0; i < len; i++){
            fft_out[hzType][i][0] = sqrt(pow((fft_out[hzType][i][0]), 2) + pow((fft_out[hzType][i][1]), 2))/len;
            fft_out[hzType][i][0] = 20*log10(fft_out[hzType][i][0]);
            DataPrimary_Fre_Temp[hzType][i] = fft_out[hzType][i][0];
        }

        //fft 采样数据解调结束
        demodule_DecData(hzType);

    }QT_CATCH(QString eMessage){
        record_log("function demodule():"+eMessage);
    }

}



/**
*  \brief  串口收数后调用解调主程序.
*  \param [in] hzType  高频低频区分
*
*
**/
void MutiSignalDecode::dbpsk_demodule(int hzType){
    QT_TRY{
        int i = 0,len = 0,start = 0;

        //解调地面数据

        Dpbsk_Demodulator(MudSigStand[hzType],DemodulatorS_PriCh[hzType],ModuleEnableStatus[hzType],Probe[hzType],DemodParam[hzType],frame_counter,hzType);

        len = Actual_Len[hzType] / 2;
        start = MseqCorrOut_PriCh_TempSize - len;

        for(i = 0 ; i < start;i++){
            MseqCorrOut_PriCh_Temp[hzType][i] = MseqCorrOut_PriCh_Temp[hzType][i+len];
        }

        for(i = 0 ; i < len ;i++){
            MseqCorrOut_PriCh_Temp[hzType][start+i] = Probe[hzType]->MseqCorrOut[i];
        }


        len = Probe[hzType]->EqSigCnt / 2;
        start = EQ_ALL_ERR_LEN - len;
        for(i = 0 ; i < start;i++){
            EqErr_PriCh_Temp[hzType][i] = EqErr_PriCh_Temp[hzType][i+len];
            EqSig_PriCh_Temp_I[hzType][i] = EqSig_PriCh_Temp_I[hzType][i+len];
            EqSig_PriCh_Temp_Q[hzType][i] = EqSig_PriCh_Temp_Q[hzType][i+len];
        }

        for(i = 0 ; i < len ;i++){
            EqErr_PriCh_Temp[hzType][start+i] = sqrt(pow(Probe[hzType]->EqErr[i * 2], 2) + pow(Probe[0]->EqErr[i * 2 + 1], 2));
            EqSig_PriCh_Temp_I[hzType][start+i] = Probe[hzType]->EqSig[i * 2];
            EqSig_PriCh_Temp_Q[hzType][start+i] = Probe[hzType]->EqSig[i * 2 + 1];
        }


        len = DemodParam[hzType]->PreSignal_Len;
        start = DataPrimary_BUF_SIZE - len;
        for(i = 0 ; i < start;i++){
            DataPrimary_Temp[hzType][i] = DataPrimary_Temp[hzType][i+len];
            Data_SignalDenoise[hzType][i] = Data_SignalDenoise[hzType][i+len];
        }

        for(i = 0 ; i < len ;i++){
            DataPrimary_Temp[hzType][start+i] = MudSigStand[hzType]->Pri[i];
            Data_SignalDenoise[hzType][start+i] = Probe[hzType]->SignalDenoise[i];
        }

        for(i = 0 ; i < DemodulatorS_PriCh[hzType]->ModuleStructFSRC->Farrow_SigLen ;i++){
            Farrow_Temp[hzType][i] = Probe[hzType]->SigBB_Frw[i];
        }
        //fft 采样数据解调开始
        for (i = 0; i <DemodParam[0]->ADC_Fs_Hz*2; i++){
            fft_in[hzType][i] = DataPrimary_Temp[hzType][i];
        }

        my_plan[hzType] = FFTW3_H::fftw_plan_dft_r2c_1d(DemodParam[0]->ADC_Fs_Hz*2, fft_in[hzType], fft_out[hzType], FFTW_ESTIMATE);
        fftw_execute(my_plan[hzType]);
        len = DataPrimary_BUF_SIZE/2;
        for(i = 0; i < len; i++){
            fft_out[hzType][i][0] = sqrt(pow((fft_out[hzType][i][0]), 2) + pow((fft_out[hzType][i][1]), 2))/len;
            fft_out[hzType][i][0] = 20*log10(fft_out[hzType][i][0]);
            DataPrimary_Fre_Temp[hzType][i] = fft_out[hzType][i][0];
        }
        //if(hzType==1){
        for (int m = 0; m < DemodulatorS_PriCh[hzType]->ModuleStructFSRC->Farrow_SigLen; m++){
            //double aa = Probe[hzType]->SigBB_Frw[m];
            //int valSigBB = round(Probe[hzType]->SigBB_Frw[m] *4096/2.5);
           // qDebug()<<"m===="<<m<<":::valSigBB==="<<valSigBB<<endl;
            ((pint16)((*(gsDlPhy_SampleInBufCtrl[hzType].pDlPhy_SampleInBuf))[gsDlPhy_SampleInBufCtrl[hzType].nFrmWp]))[gnDlPhy_Frame_RxCnt_Intermediate[hzType]]
                     = Probe[hzType]->SigBB_Frw[m] *4096/2.5;
             if(gnDlPhy_Frame_RxCnt_Intermediate[hzType]==(DLPHY_SAMPLE_PER_BIT-1)){
                 POST_DOWNLINK_DMDLR_MSG(&gsDownlinkDemodulatorMsg[hzType], gsDlPhy_SampleInBufCtrl[hzType].nFrmRp);
                 gsDlPhy_SampleInBufCtrl[hzType].nFrmRp = (gsDlPhy_SampleInBufCtrl[hzType].nFrmRp+1) & (DLPHY_SAMPLE_IN_BUF_SZ_IN_BIT-1);
                 gsDlPhy_SampleInBufCtrl[hzType].nFrmWp = (gsDlPhy_SampleInBufCtrl[hzType].nFrmWp+1) & (DLPHY_SAMPLE_IN_BUF_SZ_IN_BIT-1);
                 //emit sendToDemoudle();
                 //DownlinkDemodulator_Thread();
                 uint16 res = DownlinkDemodulator_Thread(hzType);
                // qDebug()<<"hzType is ==="<<hzType<<endl;
                 if(res != 10000 && res>=0){
                    qDebug()<<"data is ==="<<res<<endl;
                    QString qs00 = QString("%1").arg(res,2,16,QLatin1Char('0')).toUpper();
                    emit sendDeCodeData(qs00,hzType);
                 }
             }
             gnDlPhy_Frame_RxCnt_Intermediate[hzType] = gnDlPhy_Frame_RxCnt_Intermediate[hzType]+1;
             if(gnDlPhy_Frame_RxCnt_Intermediate[hzType] >= DLPHY_SAMPLE_PER_BIT)
                 gnDlPhy_Frame_RxCnt_Intermediate[hzType] = gnDlPhy_Frame_RxCnt_Intermediate[hzType]-DLPHY_SAMPLE_PER_BIT;
        }
      //  }

        //fft 采样数据解调结束
       // demodule_DecData(hzType);

    }QT_CATCH(QString eMessage){
        record_log("function demodule():"+eMessage);
    }

}


void MutiSignalDecode::free_Param()
{
    QT_TRY{
        int i = 0;

        for(i=0;i<SERIAL_PORT_COUNT;i++){
            DemodulatorDelete(DemodulatorS_PriCh[i], Probe[i], MudSigStand[i], DemodParam[i], ModuleEnableStatus[i]);

//            if(my_plan[i] != NULL){
//                fftw_destroy_plan(my_plan[i]);
//            }
            fftw_free(fft_in[i]);
            fftw_free(fft_out[i]);
            Demodulator_free(DemodParam[i]->DFE_FracEqRatio);

            //释放结构体动态内存
            free(fifoDecByte[i].Buf);
            free(fifoDec[i].Buf);
        }
        record_log("function freeParam():END");
    }QT_CATCH(QString eMessage){
        record_log("function freeParam():"+eMessage);
    }
}
